package com.kang.commons.util;

import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @program: photo_fawu
 * @description: redis数据库工具类
 * @author: K.faWu
 * @create: 2021-11-08 17:05
 **/
@Component
public class RedisUtil {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void delectStringObject(String key,Object v){
        setStringObjectByMillis(key, v, 1);
    }

    public Object getStringObject(String key){
        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        return stringObjectValueOperations.get(key);
    }
    /**
     * 根据毫秒添加
     * @param key
     * @param v
     * @param time
     */
    public void setStringObjectByMillis(String key, Object v, long time){
        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        stringObjectValueOperations.set(key,v,time, TimeUnit.MILLISECONDS);
    }

    /**
     * 根据分钟添加
     * @param key
     * @param v
     * @param time
     */
    public void setStringObjectByMinutes(String key, Object v, long time){
        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        stringObjectValueOperations.set(key,v,time, TimeUnit.MINUTES);
    }

    /**
     * 根据小时添加
     * @param key
     * @param v
     * @param time
     */
    public void setStringObjectByHours(String key, Object v,long time){
        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        stringObjectValueOperations.set(key,v,time, TimeUnit.HOURS);
    }

    public void setHash(String key, Object hk, Object hv){
        HashOperations<String, Object, Object> stringObjectObjectHashOperations = redisTemplate.opsForHash();
        stringObjectObjectHashOperations.put(key, hk, hv);
    }

    public Set getHash(String key){
        HashOperations<String, Object, Object> stringObjectObjectHashOperations = redisTemplate.opsForHash();
        Set<Object> keys = stringObjectObjectHashOperations.keys(key);
        return keys;
    }
}
